import { createRouter, createWebHistory } from 'vue-router'
import login from '../views/login.vue'
import Home from '../views/Home.vue'
import Webnet from  '../components/net/webNet.vue'
import Cainet from  '../components/net/cainet.vue'
import Othernet from  '../components/net/othernet.vue'
import HeartNote from '../components/mysplace/heartNote.vue'
import Bill from '../components/mysplace/bill.vue'
import billScreen from '../views/billScreen.vue'
import No from '../views/404.vue'
import Note from '../components/mysplace/note.vue'
import Fan from '../components/fan/fan.vue'
const routes =[
  {
    path: '/',
    redirect:'/login',
  },
  {
    path: '/login',
    component:login,
    meta: {
      title: '登入',
      // keepAlive: true // 需要被缓存
    }
  },
  {
    path: '/home',
    component:Home,
    meta:{
      title:'home',
    },
    redirect:'/webnet',
    children:[
      {
        path:'/webnet',
        component:Webnet
      },
      {
        path:'/cainet',
        component:Cainet
      },
      {
        path:'/othernet',
        component:Othernet
      },
      {
        path:'/diary',
        component:HeartNote
      },{
        path:'/bill',
        component:Bill
      },{
        path:'/note',
        component:Note
      },{
        path:'/fan',
        component:Fan
      }
    ]
  },
  {
    path:'/billScreen',
    component:billScreen
  },
  {
    path:"/:catchAll(.*)",//捕获一切不存在的路由
    component:No
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  // scrollBehavior (to, from, savedPosition) {
  //   if (savedPosition) {
  //     return savedPosition
  //   } else {
  //     return {x: 0, y: 0}
  //   }
  // }
})

router.beforeEach((to,from,next)=>{
  if(to.meta&&to.meta.title){
    document.title=to.meta.title
  }
  if(localStorage.getItem('user')){
      if(to.path=='/login'){
        next({path: '/home'})
      }else{
        next()
      }
  }else{
    if(to.path=='/'||to.path=='/login'){
      next()
    }else{
      next({path:'/login'})
    }
      
  }
 
})

export default router
